#include <QtWidgets>
#include <QtWebKitWidgets>
#include <QDebug>

#include "window.h"

#define SEARCH_API "http://www.baidu.com/s?wd="

Window::Window(QWidget *parent)
    : QMainWindow(parent),siteStr("sohu.com"),isFinshed(false)
{
    setupUi(this);
    webView->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    connect(seachBtn,SIGNAL(clicked()),this,SLOT(on_seach_btn_clicked()));
//    connect(checkBox_2,SIGNAL(clicked(bool)),this,SLOT(on_checkBox_clicked(bool)));
//    connect(checkBox,SIGNAL(clicked(bool)),this,SLOT(on_checkBox_clicked(bool)));
    connect(QApplication::clipboard(),SIGNAL(dataChanged()),this,SLOT(clipboardChanged()));
    m_pConfigSet = new ConfigSet("./config.ini");
    initCheckBox();
    setMouseTracking(true);
}
Window::~Window(){
    QMap<QString,QWebView*>::iterator it; //遍历map
    for ( it = m_webViewMap.begin(); it != m_webViewMap.end(); it++ ) {
        it.value()->stop();
        it.value()->destroyed();
        delete it.value();
    }
}


void Window::setUrl(const QUrl &url)
{    
    webView->setUrl(url);
}

void Window::mouseReleaseBtn()
{
    qDebug()<<"mouseReleaseBtn";
}
    
void Window::on_webView_loadFinished()
{
    //treeWidget->clear();

//    QWebFrame *frame = webView->page()->mainFrame();
//    QWebElement document = frame->documentElement();
//    //qDebug("%s",document.toOuterXml().toStdString().c_str());

    //examineChildElements(document, treeWidget->invisibleRootItem());
//    QMessageBox::information(this,"load finished","ttt");
    /*if(isFinshed == false){
        QWebView *webView = (QWebView*)sender();
        qDebug()<<"----------------------------------------"<<endl;
        QWebElement e = webView->page()->mainFrame()->findFirstElement("#wrapper_wrapper");
        QWebElement ePage = webView->page()->mainFrame()->findFirstElement("#page");
        QString xmlStr = e.toInnerXml() + ePage.toInnerXml();
        qDebug()<<xmlStr;
        qDebug()<<"----------------------------------------"<<endl;
        QString html = saveTempHtmlFromXML(xmlStr);
        webView->setHtml(html);
        isFinshed = true;
    }*/

}

void Window::on_seach_btn_clicked(){
//    QString seachUrlText = QString(SEARCH_API)+QString(lineEdit->text())+
//           QString(" site:")+siteStr;
    //setUrl(QUrl(seachUrlText));
    isFinshed = false;
    setUrl(SEARCH_API,lineEdit->text());
}

void Window::examineChildElements(const QWebElement &parentElement,
                                  QTreeWidgetItem *parentItem)
{
    QWebElement element = parentElement.firstChild();
    while (!element.isNull()) {

        QTreeWidgetItem *item = new QTreeWidgetItem();
        item->setText(0, element.tagName());
        parentItem->addChild(item);

        examineChildElements(element, item);

        element = element.nextSibling();
    }
}

QWebView* Window::addWebView(QString defualtUrlStr){
    QWebView *webView = new QWebView();
    webView->page()->setLinkDelegationPolicy(QWebPage::DelegateAllLinks);
    webView->setUrl(QUrl(defualtUrlStr));
    webViewLayout->addWidget(webView);
    connect(webView,SIGNAL(linkClicked(QUrl)),this,SLOT(on_webView_linkClicked(QUrl)));
    connect(webView,SIGNAL(loadFinished(bool)),this,SLOT(on_webView_loadFinished()));
    return webView;
}

void Window::initCheckBox()
{
    m_pConfigSet->readConfig();
    if(m_pConfigSet->m_vector.isEmpty()== false){
        webView->setUrl(QUrl("http://www.baidu.com"));
       m_webViewMap[m_pConfigSet->m_vector.first()] = webView;
   }
    int i = 0;
    for(QVector<QString>::iterator it = m_pConfigSet->m_vector.begin();
        it!=m_pConfigSet->m_vector.end(); it++){
        QCheckBox *checkBox = new QCheckBox();
        checkBox->setText(*it);
        connect(checkBox,SIGNAL(clicked(bool)),this,SLOT(on_checkBox_clicked(bool)));
        checkBoxLayout->addWidget(checkBox);
        if(i == 0){
            checkBox->setCheckState(Qt::Checked);
        }
        i++;
    }
}

bool Window::fixTheUrlStr(QString searchUrl,QString keyword,QString &urlStr){
    QString seach_keyword = keyword;
    bool isNeedFixHost = false;
    if(isSeachSite(keyword,seach_keyword)){
        urlStr = searchUrl +seach_keyword;
        isNeedFixHost = true;
    }else if(isSeachTitle(keyword,seach_keyword)) {
        urlStr = searchUrl + seach_keyword;
        isNeedFixHost = false;
    }else if(isSeachDomain(keyword,seach_keyword)){
        urlStr = searchUrl + seach_keyword;
        isNeedFixHost = false;
    }else if(isSeachIntitle(keyword,seach_keyword)){
        urlStr = searchUrl + seach_keyword;
        isNeedFixHost = false;
    }else if (isSeachInurl(keyword,seach_keyword)) {
        urlStr = searchUrl + seach_keyword;
        isNeedFixHost = false;
    }else {
        urlStr = searchUrl +seach_keyword;
        isNeedFixHost = false;
    }
    return isNeedFixHost;
}

void Window::setUrl(QString searchUrl, QString keyword)
{
    QString urlStr ;
    bool isNeedFixHost = fixTheUrlStr(searchUrl,keyword,urlStr);
    for(QMap<QString,QWebView*>::iterator it = m_webViewMap.begin();it != m_webViewMap.end();
        it++){
        QString temp = "";
        if(isNeedFixHost){
            temp = urlStr + it.key();
        }else{
            temp = urlStr;
        }
        it.value()->setUrl(QUrl(temp));
    }
}

QString Window::saveTempHtmlFromXML(QString xmlStr, QString tempName)
{
    QFile file_head("head.html");
    if(!file_head.open(QIODevice::ReadOnly|QIODevice::Text)){
        return NULL;
    }
    QTextStream in_Head(&file_head);
    QString headStr;
    while(!in_Head.atEnd()){
        QString tempStr = in_Head.readLine();
        headStr += tempStr;
    }
    file_head.close();

    QFile file_end("end.html");
    if(!file_end.open(QIODevice::ReadOnly|QIODevice::Text)){
        return NULL;
    }
    QTextStream in_End(&file_end);
    QString endStr;
    while(!in_End.atEnd()){
        QString tempStr = in_End.readLine();
        endStr += tempStr;
    }
    file_end.close();

    QFile file(tempName);
    if(!file.open(QIODevice::WriteOnly|QIODevice::Text)){
        return NULL;
    }
    QTextStream out(&file);
    out<<headStr<<xmlStr<<endStr;
    file.close();
    return headStr+xmlStr+endStr;
}

bool Window::isSeachSite(QString keyword,QString &seach_keyword)
{
    int i = keyword.indexOf(QRegExp("site:"));
    if(i != -1){
        seach_keyword = keyword;
        return true;
    }else{
        seach_keyword = keyword;
        return false;
    }
}

bool Window::isSeachTitle(QString keyword,QString &seach_keyword)
{
    int i = keyword.indexOf(QRegExp("title:"));
    if(i != -1){
        seach_keyword = keyword;
        return true;
    }else{
        seach_keyword = keyword;
        return false;
    }
}

bool Window::isSeachDomain(QString keyword,QString &seach_keyword)
{
    int i = keyword.indexOf(QRegExp("domain:"));
    if(i != -1){
        seach_keyword = keyword;
        return true;
    }else{
        seach_keyword = keyword;
        return false;
    }
}

bool Window::isSeachInurl(QString keyword, QString &seach_keyword)
{
    int i = keyword.indexOf(QRegExp("inurl:"));
    if(-1 != i){
        seach_keyword = keyword;
        return true;
    }else{
        seach_keyword = keyword;
        return false;
    }
}

bool Window::isSeachIntitle(QString keyword, QString &seach_keyword)
{
    int i = keyword.indexOf(QRegExp("intitle:"));
    if(-1 != i){
        seach_keyword = keyword;
        return true;
    }else{
        seach_keyword = keyword;
        return false;
    }
}

void Window::on_webView_linkClicked(const QUrl &arg1)
{
    QDesktopServices::openUrl(arg1);
}


void Window::on_checkBox_clicked(bool checked)
{
    QCheckBox *checkBox = (QCheckBox*)sender();
    siteStr = checkBox->text();
    if(checked){
        QString urlStr = "http://www."+siteStr;
        if(lineEdit->text().length() >0){
            bool isNeedFixHost = fixTheUrlStr(SEARCH_API,lineEdit->text(),urlStr);
            if(isNeedFixHost){
                urlStr = urlStr + siteStr;
            }
        }
        if(m_webViewMap[siteStr] != NULL){
            m_webViewMap[siteStr]->show();
        }else{
            this->m_webViewMap.insert(siteStr,addWebView(urlStr));
        }
    }else{
        for(QMap<QString,QWebView*>::iterator it = m_webViewMap.begin();it!=m_webViewMap.end();it++){
            if(it.key() == siteStr){
                it.value()->hide();
                //it.value()->destroyed();
                //delete it.value();
                //m_webViewMap.erase(it);
            }
        }
    }
}

void Window::on_lineEdit_returnPressed()
{
    on_seach_btn_clicked();
}

void Window::setClipboard()
{
    QClipboard *clipboard = QApplication::clipboard();
    clipboard->setText(lineEdit->text());
}

void Window::getClipboard()
{
    QClipboard *clipboard = QApplication::clipboard();
    lineEdit->setText(clipboard->text());
}

void Window::clipboardChanged()
{
    QClipboard *clipboard = QApplication::clipboard();
    lineEdit->setText(lineEdit->text() + " "+ clipboard->text());
}

